package com.app.couponsharelife.ui.main.seeding

import android.annotation.SuppressLint
import android.content.*
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.AnimationDrawable
import android.net.Uri
import android.os.Bundle
import android.text.Html
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.baichuan.trade.biz.login.AlibcLogin
import com.alibaba.baichuan.trade.biz.login.AlibcLoginCallback
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import com.google.gson.Gson
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.*
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.dialog.BotShareDialog
import com.app.couponsharelife.ui.listener.MyMultiPurposeListener
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.home.good.GoodDetailActivity
import com.app.couponsharelife.ui.main.home.good.ScanPicActivity
import com.app.couponsharelife.ui.main.home.shopweb.ShopWebActivity
import com.app.couponsharelife.ui.main.login.NewLoginActivity
import com.app.couponsharelife.ui.view.GoodSharePicView
import com.app.couponsharelife.ui.view.MImageGetter
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.DataUtils
import com.app.couponsharelife.utils.LoadUtils
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXImageObject
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.fragment_single_commodity.*
import kotlinx.android.synthetic.main.single_commodity_imagitem.view.*
import kotlinx.android.synthetic.main.single_commodity_rvitem.view.*
import okhttp3.MediaType
import okhttp3.RequestBody
import java.io.File
import java.io.Serializable
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

/**
 *Created by xct on 2019/5/7
 *Description:精选单品
 */
class SingleCommodityFragment:LazyFragment() {
    private var pageIndex=1
    private var adapter:MyAdapter?=null
    private var dataList= arrayListOf<SingleCommodityData>()
    private val simpleDateFormat = SimpleDateFormat("MM.dd HH:mm", Locale.getDefault())
    private var mTaoKouLing=""
    private var mShareUrl = ""
    private var picFile: File? = null
    private var shareType = 0
    private var viewType=1
    private var api: IWXAPI? = null
    private var bitmaps = arrayListOf<Bitmap>()
    private var minId="1"
    private var copy_content=""
    companion object {
        fun newInstance(): SingleCommodityFragment {
            val fragment = SingleCommodityFragment()
            fragment.arguments = Bundle()
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.fragment_single_commodity

    override fun initViews() {
        setRefresh()
        singleCommodity_rv.layoutManager=LinearLayoutManager(context)
        adapter=MyAdapter()
        singleCommodity_rv.adapter=adapter
    }
    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        val animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        singleCommodity_smart.setEnableNestedScroll(true)
        singleCommodity_smart.setOnMultiPurposeListener(object : MyMultiPurposeListener {
            override fun headerReleased() {
                animationDrawable.start()
            }

            override fun headerMoving(percent: Float) {
                setAnima(percent)
            }

            override fun headerFinish() {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable.stop()
            }

            override fun loadMore() {
                getData(false)
            }

            override fun refresh() {
                minId="1"
                getData(true)
            }

        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }
    override fun lazyLoad() {
        getData(false)
    }
    private fun getData(isRefresh:Boolean){
        showProgressDialog("加载中...")
        val map= HashMap<String,String>()
        map["minId"]=minId
        RetrofitWorker.retrofitWorker.getCircleOfFriends(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<SingleCommodityDataBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<SingleCommodityDataBean>) {
                        dismissProgressDialog()
                        if (isRefresh){
                            singleCommodity_smart.finishRefresh()
                        }else{
                            if (minId!="1"){
                                singleCommodity_smart.finishLoadMore()
                            }
                        }
                        if (minId=="1"){
                            dataList.clear()
                        }
                        if (it.code==200&&it.data!=null&&it.data!!.data!=null){
                            if (it.data!!.data!!.isNotEmpty()){
                                if (minId=="1"){
                                    singleCommodity_llerror.visibility=View.GONE
                                    singleCommodity_rv.visibility=View.VISIBLE
                                }
                                minId=it.data!!.min_id?:""
                                dataList.addAll(it.data!!.data!!)
                                adapter!!.notifyDataSetChanged()
                            }else{
                                if (minId=="1"){
                                    singleCommodity_llerror.visibility=View.VISIBLE
                                    singleCommodity_rv.visibility=View.GONE
                                }else{
                                    singleCommodity_smart.finishLoadMoreWithNoMoreData()
                                }
                            }
                        }else{
                            singleCommodity_smart.finishLoadMoreWithNoMoreData()
                            if (minId=="1"){
                                singleCommodity_llerror.visibility=View.VISIBLE
                                singleCommodity_rv.visibility=View.GONE
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        singleCommodity_llerror.visibility=View.VISIBLE
                        singleCommodity_rv.visibility=View.GONE
                        if (isRefresh){
                            singleCommodity_smart.finishRefresh()
                        }
                        singleCommodity_smart.finishLoadMoreWithNoMoreData()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }
    private fun goShare(dataBean:SingleCommodityData,imagList: ArrayList<String>) {
        if (AppUtils.checkUserLogin())  // && judgeAdzoneIdExist()
            BotShareDialog(context!!, R.style.DialogStyle, object : OnClickListener {
                override fun click(arg1: Int, arg2: Any) {
                    shareType = arg1
                    //getTaoKouLing(dataBean,imagList,true)
                    copy_content=dataBean.copy_content?:""
                    getTBGoods(dataBean.itemid?:"",true)
                }
            }).show()
        else
        //startActivity(Intent(context, LoginActivity::class.java))
            startActivity(Intent(context, NewLoginActivity::class.java))
    }
    private fun taobaoLogin(){
        showProgressDialog("请稍后")
        val alibcLogin = AlibcLogin.getInstance()
        alibcLogin.showLogin(object : AlibcLoginCallback {
            override fun onSuccess(p0: Int) {
                //showToastMsg("登录成功 ")
                //获取淘宝用户信息
                //Log.i("eee", "获取淘宝用户信息: "+AlibcLogin.getInstance().session)
                dismissProgressDialog()
                //getAliLoginUrl()
                getAliLoginUrl()
            }

            override fun onFailure(p0: Int, p1: String?) {
                //showToastMsg("登录失败")
                dismissProgressDialog()
            }
        })
    }
    private fun getTBGoods(goodsID:String,isShare:Boolean){
        val url="https://item.taobao.com/item.htm?id=$goodsID"
        val map=HashMap<String,String>()
        map["pageNo"]="1"
        map["pageSize"]="1"
        map["userId"]= AppUtils.getString(Contacts.USERID,"")
        map["keyword"]=url
        RetrofitWorker.retrofitWorker.getTBGoodsList(map)
                .subscribeOn(Schedulers.io())
                .map { DataUtils().taobaoSearchData(it) }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<SearchTBGoodsListBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<SearchTBGoodsListBean>) {
                        if (it.data!=null&&it.data!!.recordss.isNotEmpty()){
                            val taobaoGoodBean=it.data!!.recordss[0]
                            getTaoKouLing(taobaoGoodBean,isShare)
                        }else{
                            showToastMsg("该商品已下架！")
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            //Log.e("eee","---->"+e.toString())
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }
    private fun getTaoKouLing(goodBean:TaobaoGoodBean,isShare:Boolean) {
        val rlid= AppUtils.getString(Contacts.ADZONE_ID, "")
        if (rlid.isEmpty()){
            //getAliLoginUrl()
            taobaoLogin()
            return
        }
        val map = HashMap<String, String>()
        map["text"] = goodBean!!.title.replace("@", "").replace("%","％")
        /*val url = if (goodBean!!.coupon_share_url_new!= "") goodBean!!.coupon_share_url_new else {
            if (goodBean!!.coupon_share_url != "https:" && goodBean!!.coupon_share_url != "") goodBean!!.coupon_share_url else goodBean!!.url
        }*/
        val url = if (goodBean!!.coupon_share_url_new != "") goodBean!!.coupon_share_url_new else {
            if (goodBean!!.coupon_share_url != "https:" && goodBean!!.coupon_share_url != "") goodBean!!.coupon_share_url else goodBean!!.url
        }
        if (url == "") {
            showToastMsg("该商品暂时不能分享")
        }
        map["url"] =url
        map["relationId"] = ""
        map["userId"] = AppUtils.getString(Contacts.USERID,"")
        map["logo"] = goodBean.pict_url as String?:""
        map["timestamp"] = (System.currentTimeMillis()).toString()
        map["sign"] = AppUtils.getMapString(map)
        RetrofitWorker.retrofitWorker.getTKLing(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        dismissProgressDialog()
                        if (200==it.code&&it.data!=null){
                            if (it.data!!.isNotEmpty()) {
                                mTaoKouLing = it.data.toString()
                                if (isShare) {
                                    saveShareItemInfo(goodBean)
                                }else{
                                    copyContent(mTaoKouLing)
                                }
                            } else {
                                showToastMsg("淘口令获取失败，请重试")
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错！")
                        }
                    }
                })
    }
    private fun getAliLoginUrl(){
        showProgressDialog("加载中...")
        val map = HashMap<String, String>()
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        RetrofitWorker.retrofitWorker.getAuthUrl(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        dismissProgressDialog()
                        if (200==it.code){
                            val url=it.data?:""
                            if (url.isNotEmpty()){
                                val intent= Intent(context, ShopWebActivity::class.java)
                                intent.putExtra("url", url)
                                intent.putExtra("name", "淘宝授权")
                                startActivity(intent)
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            if ("502"==e.code.toString()){

                            }
                        }
                    }
                })
    }
    private fun saveShareItemInfo(dataBean:TaobaoGoodBean) {
        val map = HashMap<String, String>()
        map["code"] = mTaoKouLing
        map["imgPath"] = dataBean.pict_url as String?:""
        map["itemId"] = dataBean.num_iid?:""
        map["newPrice"] = dataBean!!.final_price
        map["nick"]=dataBean!!.shop_title
        map["reservePrice"]=dataBean!!.reserve_price
        map["smallImages"]=Gson().toJson(dataBean!!.images) //goodBean!!.images.toString()
        map["couponInfo"]=dataBean!!.coupon_price
        map["pageSource"]="quan11"
        map["volume"]=(dataBean!!.volume?:"").replace("月销","")
        map["userType"]=when(dataBean!!.goodsSource){
            "淘宝"->{"0"}
            "天猫"->{"1"}
            "拼多多"->{"3"}
            "京东"->{"2"}
            else->{"0"}
        }
        map["couponCount"]=dataBean!!.coupon_remain_count?:"0"
        map["oldPrice"] = dataBean!!.original_price

        map["title"] = dataBean!!.title.replace("%","％")
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        RetrofitWorker.retrofitWorker.newSaveShareItemInfo(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .map {
                    if (it.data != null) {
                        it.data =it.data
                    }
                    it
                }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        dismissProgressDialog()
                        if (200==it.code&&it.data!=null){
                            mShareUrl =it.data!!
                            initSharePic(dataBean)
                        }else{
                            showToastMsg("分享链接获取失败，请重试")
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错")
                            Log.e("eee",e.toString())
                        }
                    }
                })
    }
    @SuppressLint("CheckResult")
    private fun initSharePic(dataBean:TaobaoGoodBean) {
        picFile = null
        bitmaps.clear()
        val goodBean=TaobaoGoodBean()
        goodBean.item_id=dataBean.num_iid?:""
        goodBean.volume="0"
        goodBean.goodsSource1="好单库"
        goodBean.small_images=""
        goodBean.title=dataBean.title?:""
        goodBean.original_price=dataBean.original_price?:"0"
        goodBean.userType=R.drawable.goods_tb
        goodBean.final_price=dataBean.final_price?:"0"
        goodBean.has_coupon=true
        goodBean.coupon_price=dataBean.coupon_price?:"0"
        goodBean.pict_url=""
        if (dataBean != null) {
            if (shareType == 1) {
                val view = GoodSharePicView(mShareUrl, goodBean, context!!)
                Glide.with(context!!).load(dataBean.pict_url as String)
                        .downloadOnly(object : SimpleTarget<File>() {
                            override fun onResourceReady(resource: File, transition: Transition<in File>?) {
                                view.setImage(resource)
                                picFile = AppUtils.saveBitmap(view.generateBitmap(), "shareImg0.jpg", false)
                                shareSingleBitmap(dataBean)
                            }
                        })
            } else {
                for (i in 0 until dataBean.images.size) {
                    if (i == 0) {
                        val view = GoodSharePicView(mShareUrl, goodBean, context!!)
                        Glide.with(context!!).load(dataBean.images[i])
                                .downloadOnly(object : SimpleTarget<File>() {
                                    override fun onResourceReady(resource: File, transition: Transition<in File>?) {
                                        view.setImage(resource)
                                        picFile = AppUtils.saveBitmap(view.generateBitmap(), "shareImg0.jpg", false)
                                        if (bitmaps.size == dataBean.images.size - 1)
                                            if (dataBean.images.size == 1)
                                                shareSingleBitmap(dataBean)
                                            else
                                                shareMultiBitmap(dataBean)
                                    }
                                })
                    } else {
                        Glide.with(context!!)
                                .asBitmap()
                                .load(dataBean.images[i])
                                .listener(object : RequestListener<Bitmap> {
                                    override fun onLoadFailed(e: GlideException?, model: Any, target: Target<Bitmap>, isFirstResource: Boolean): Boolean {
                                        println(e?.message)
                                        showToastMsg("分享图片生成失败，请重试")
                                        return false
                                    }

                                    override fun onResourceReady(resource: Bitmap?, model: Any, target: Target<Bitmap>, dataSource: DataSource, isFirstResource: Boolean): Boolean {
                                        if (resource != null) {
                                            bitmaps.add(resource)
                                            if (bitmaps.size == dataBean.images.size - 1 && picFile != null) shareMultiBitmap(dataBean)
                                            return true
                                        }
                                        return false
                                    }
                                }).into(AppUtils.getDisplayMetrics(context!!).widthPixels, AppUtils.getDisplayMetrics(context!!).widthPixels)
                    }
                }
            }
        } else {
            showToastMsg("分享失败，请重试")
            dismissProgressDialog()
        }
    }
    private fun shareMultiBitmap(dataBean:TaobaoGoodBean) {
        if (picFile != null) {
            val imageUris = java.util.ArrayList<Uri>()
            imageUris.add(Uri.fromFile(picFile))
            var index = 1
            for (bitmap in bitmaps) {
                imageUris.add(Uri.fromFile(AppUtils.saveBitmap(bitmap, "shareImg$index.jpg", false)))
                index++
            }
            if (imageUris.isEmpty()) {
                showToastMsg("请选择要分享的图片")
                return
            }
            goShareMulti(dataBean,imageUris)
        } else if (bitmaps.size==dataBean.images.size){
            val imageUris = java.util.ArrayList<Uri>()
            var index = 1
            for (bitmap in bitmaps) {
                imageUris.add(Uri.fromFile(AppUtils.saveBitmap(bitmap, "shareImg$index.jpg", false)))
                index++
            }
            if (imageUris.isEmpty()) {
                showToastMsg("请选择要分享的图片")
                return
            }
            goShareMulti(dataBean,imageUris)
        }else
            showToastMsg("数据错误，请重试")
        dismissProgressDialog()
        dayShare()
    }
    private fun goShareMulti(dataBean:TaobaoGoodBean,imageUris: java.util.ArrayList<Uri>){
        var intent = Intent()
        val comp = if (shareType == 0)
            ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI")
        else
            ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI")
        intent.component = comp
        intent.action = Intent.ACTION_SEND_MULTIPLE
        intent.type = "image/*"
        val str=(copy_content).replace("&lt;","<").replace("&gt;",">").replace("<br>","\n")
        copyContent(str)
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris)
        intent = Intent.createChooser(intent, "商品分享")
        startActivity(intent)
    }
    private fun shareSingleBitmap(dataBean:TaobaoGoodBean) {
        if (picFile == null) {
            showToastMsg("数据错误，请重试")
            return
        }
        val str=(copy_content).replace("&lt;","<").replace("&gt;",">").replace("<br>","\n")
        copyContent(str)
        val bitmap = BitmapFactory.decodeFile(picFile!!.absolutePath)

        val image = WXImageObject(bitmap)

        val msg = WXMediaMessage()
        msg.mediaObject = image

        val thumb = Bitmap.createScaledBitmap(bitmap, 150, 150, true)
        msg.thumbData = AppUtils.bmpToByteArray(thumb, true)

        val req = SendMessageToWX.Req()    //创建一个请求对象
        req.message = msg  //把msg放入请求对象中
        if (shareType == 1)
            req.scene = SendMessageToWX.Req.WXSceneTimeline    //设置发送到朋友圈
        else
            req.scene = SendMessageToWX.Req.WXSceneSession   //设置发送给朋友
        req.transaction = AppUtils.buildTransaction("img")  //这个tag要唯一,用于在回调中分辨是哪个分享请求
        if (api == null) api = WXAPIFactory.createWXAPI(context, Contacts.WECHAT_APP_ID)
        api!!.sendReq(req)   //如果调用成功微信,会返回true
        dismissProgressDialog()
        dayShare()
    }
    private fun copyContent(content: String) {
        //获取剪贴板管理器：
        val cm = activity!!.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建普通字符型ClipData
        val mClipData = ClipData.newPlainText("Label", content)
        // 将ClipData内容放到系统剪贴板里。
        cm.primaryClip = mClipData
        showToastMsg("复制成功")
    }
    private fun dayShare(){
        val map = HashMap<String, String>()
        map["userId"]= AppUtils.getString(Contacts.USERID,"")
        RetrofitWorker.retrofitWorker.shareDay(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        if (it.code==200){
                            //appShareUrl=it.data!!
                        }
                    }

                    override fun onError(e: Throwable) {

                    }
                })
    }
    private inner class MyAdapter:RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view= LayoutInflater.from(parent.context).inflate(R.layout.single_commodity_rvitem,parent,false)
            return MyHolder(view)
        }

        override fun getItemCount(): Int {
            return dataList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (dataList.isNotEmpty()) {
                if (holder is MyHolder) {
                    val singleCommodityData=dataList[position]
                    val time=singleCommodityData.show_time?:System.currentTimeMillis().toString()
                    val content = "<font color=\"#FF0038\">查看详情</font>"
                    var html="${singleCommodityData.copy_content} $content"
                    html=html.replace("&lt;","<").replace("&gt;",">")
                    holder.tvTitle!!.text = Html.fromHtml(html)
                    holder.tvPrice!!.text="原价：${singleCommodityData.itemprice}，券后：${singleCommodityData.itemendprice}"
                    var pinglun=(singleCommodityData.copy_comment?:"").replace("&lt;","<").replace("&gt;",">")
                    holder.tvPingLun!!.text=Html.fromHtml(pinglun,MImageGetter(context!!,holder.tvPingLun!!),null)
                    holder.tvShare!!.text=singleCommodityData.dummy_click_statistics?:"0"
                    holder.tvTime!!.text=if (time.isNotEmpty()){
                        if (time.length>10){
                            simpleDateFormat.format(time.toLong())
                        }else{
                            simpleDateFormat.format(time.toLong()*1000)
                        }
                    }else{
                        simpleDateFormat.format(System.currentTimeMillis())
                    }
                    var imags=singleCommodityData.itempic?:""
                    val imagList= arrayListOf<String>()
                    if (imags.isNotEmpty()){
                        imags=imags.replace("[","").replace("]","").replace("\"","")
                        val arr=imags.split(",")
                        imagList.clear()
                        imagList.addAll(arr)
                    }
                    holder.rvGoodsImag!!.layoutManager=GridLayoutManager(context,3)
                    holder.rvGoodsImag!!.adapter=MyImagAdapter(imagList)
                    holder.itemView.setOnClickListener {
                        val goodBean=TaobaoGoodBean()
                        goodBean.item_id=singleCommodityData.itemid?:""
                        goodBean.volume="0"
                        goodBean.goodsSource1="好单库"
                        val str=(singleCommodityData.copy_content?:"").replace("&lt;","<").replace("&gt;",">").replace("<br>","")
                        goodBean.goodsWenAn=str
                        goodBean.small_images=""
                        goodBean.pict_url=""
                        val intent = Intent(context, GoodDetailActivity::class.java)
                        intent.putExtra("good", goodBean)
                        startActivity(intent)
                    }
                    holder.tvShare!!.setOnClickListener {
                        goShare(singleCommodityData,imagList)
                    }
                    holder.llCode!!.setOnClickListener {
                        //getTaoKouLing(singleCommodityData.itemid?:"",false)
                        copy_content=singleCommodityData.copy_content?:""
                        getTBGoods(singleCommodityData.itemid?:"",false)
                    }
                    holder.llPinglun!!.setOnClickListener {
                        val str=(singleCommodityData.copy_comment?:"").replace("&lt;","<").replace("&gt;",">").replace("<br>","\n")
                        copyContent(str)
                    }
                }
            }
        }
    }
    private inner class MyHolder(itemview:View):RecyclerView.ViewHolder(itemview){
        var ivHead:ImageView?=null
        var tvNikeName:TextView?=null
        var tvTime:TextView?=null
        var tvShare:TextView?=null
        var tvTitle:TextView?=null
        var rvGoodsImag:RecyclerView?=null
        var llCode:LinearLayout?=null
        var tvPrice:TextView?=null
        var llPinglun:LinearLayout?=null
        var tvPingLun:TextView?=null
        init {
            ivHead=itemview.ivHead
            tvNikeName=itemview.tvNikeName
            tvTime=itemview.tvTime
            tvShare=itemview.tvShare
            tvTitle=itemview.tvTitle
            rvGoodsImag=itemview.rvGoodsImag
            llCode=itemview.llCode
            tvPrice=itemview.tvPrice
            llPinglun=itemview.llPinglun
            tvPingLun=itemview.tvPingLun
        }
    }
    private inner class MyImagAdapter(val imagList:ArrayList<String>):RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view= LayoutInflater.from(parent.context).inflate(R.layout.single_commodity_imagitem,parent,false)
            return MyImagHolder(view)
        }

        override fun getItemCount(): Int {
            return imagList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (imagList.isNotEmpty()){
                if (holder is MyImagHolder){
                    val url=imagList[position]+"_310x310.jpg"
                    LoadUtils().loadRoundImag(context!!,holder.imag!!,url,R.drawable.ic_good_place_holder,5)
                    holder.itemView.setOnClickListener {
                        val intent = Intent(context!!, ScanPicActivity::class.java)
                        intent.putExtra("pics", imagList as Serializable)
                        intent.putExtra("position", position)
                        startActivity(intent)
                    }
                }
            }
        }
    }
    private inner class MyImagHolder(itemview:View):RecyclerView.ViewHolder(itemview){
        var imag:ImageView?=null
        init {
            imag=itemview.ivGoods
        }
    }
}